package DXQclient;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.io.InputStreamReader;

import HGbet.BETRESINDEX;

import HGbet.BetSettings;
import HGbet.HGbethttp;
import HGclient.DXQdetailsWindow;
import HGclient.GameDetails;
import HGclient.HGODDSINDEX;
import P8.Common;
import P8.SoundThread;
import P8.StoneAgeClient;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import javax.swing.JOptionPane;

import org.python.antlr.PythonParser.return_stmt_return;

public class DXQclientManager {
	
	
	public  Vector<String> dxqs = new Vector<String>();
	{
	dxqs.add("2");
	dxqs.add("2/2.5");
	dxqs.add("2.5");
	
	}
	
	 NumberFormat nf = NumberFormat.getInstance();
	
	 
	 public String account = "";
	 
	 public boolean bet = false;
	 
	 public static boolean startBet = false;
	
	public  HGbethttp hgbet = null;
	
	public  Vector<String> soundalready = new  Vector<String>();

	public  DXQdetailsWindow dxqDetailsWnd = new DXQdetailsWindow(this, hgbet);
	

	

	
	public BetSettings betsetWnd = new BetSettings(this);
	
	public  Vector<String[]> BetListVec = new Vector<String[]>();
	
	private  ReadWriteLock lockeBetListVecDetails = new ReentrantReadWriteLock();
	
	boolean online = false;
	
	public void setOnline(boolean online) {
		this.online = online;
	}
	
	public boolean getOnline() {
		return online;
	}
	
	
	
	
	public  boolean recoverBetlistVecfromefile(){
		
		try{
			
			SimpleDateFormat dfmin = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
			
			Calendar currentTime = Calendar.getInstance();
			
			String folder = getAccount() + "/";
			
			if(currentTime.get(Calendar.HOUR_OF_DAY) >= 12){
				folder += dfmin.format(currentTime.getTimeInMillis());
			}else{
				currentTime.add(Calendar.DAY_OF_MONTH, -1);
				folder += dfmin.format(currentTime.getTimeInMillis());
			}
			
			
			//读取改目录下所有文件:
			File filefolder = new File("hgbetdata/" + folder + "/");
			
			if(!filefolder.exists()){
				return true;
			}
			
			File flist[] = filefolder.listFiles();
			
			int linenum = 0;
			
			for(File f : flist){
				if(f.isDirectory()){
					//System.out.println("fuck directory here");
				}else{
					//System.out.println(f.getAbsolutePath());
					//
					
					
					BufferedReader freader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF-8"));
					
					String str = "";
					
					linenum = 0;
					
					while ((str = freader.readLine()) != null) {
						
						String[] contents = str.split(",");
						
						
						BetListVec.add(contents);
						
							
						}
					
					
					
					
					if(null != freader){
						freader.close();
					}
					
					
				}
				
				
				
				
			}
			
			
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		
		
	}
	


	public  boolean saveBetlistVectofile(){
		try{
			
			SimpleDateFormat dfmin = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
			
			Calendar currentTime = Calendar.getInstance();
			
			String folder = getAccount() + "/";
			
			File filefolder = new File("hgbetdata/" + folder + "/");
			
			if(!filefolder.exists()){
				filefolder.mkdir();
			}
			
			if(currentTime.get(Calendar.HOUR_OF_DAY) >= 12){
				folder += dfmin.format(currentTime.getTimeInMillis());
			}else{
				currentTime.add(Calendar.DAY_OF_MONTH, -1);
				folder += dfmin.format(currentTime.getTimeInMillis());
			}
			
			filefolder = new File("hgbetdata/" + folder + "/");
			
			if(!filefolder.exists()){
				filefolder.mkdir();
			}
			
			String filenametmp = "betres"
					+ ".data";
			
			
			
			
			
			File file = new File("hgbetdata/" + folder+"/"+filenametmp);
			
			if(!file.exists()){
				System.out.println("create hgbetdata/" + filenametmp);
				
				
				
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));
			
			
			
			
			for(int i = 0; i < BetListVec.size(); i++){
				
				String[] item = BetListVec.elementAt(i);
				
				if(item[BETRESINDEX.BETRES.ordinal()].equals("-")){
					continue;
				}
				
				String str = "";
				for(int j = 0; j < item.length; j++){
					if(j == 0){
						str = item[j];
					}else{
						str = str + "," + item[j];
					}
				}
				
				fwlocal.append(str);
				fwlocal.newLine();
				fwlocal.flush();

			}
			
			fwlocal.close();
			
			
			
			return true;
			
			
		}catch(Exception e){
			e.printStackTrace();
			
			
			
			
			return false;
		}
	}
	
	
	/**
	 * 获取账号
	 */
	public String getAccount() {
		return account;
	}
	
	public void setBet(boolean b){
		bet = b;
	}
	
	public boolean getBet(){
		return bet;
	}
	
	public static void setStartBet(boolean b){
		startBet = b;
	}
	
	public void setAccount(String acc){
		account = acc;
	}
	
	
	
	public  void updateDXQ(Vector<GameDetails> dxq){
		dxqDetailsWnd.updateGameDetailsVec(dxq);
		
		//sound
		try{
		SimpleDateFormat dfmin = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		long currenttime = System.currentTimeMillis();
		
		

		

		
		
		
		//construct bet list
		
		
		lockeBetListVecDetails.writeLock().lock();
		
		if(getDXQgrabstate()== true ){
			
			
			
			//if(autobet == true){
			if(bet == true && startBet == true){
				constructbetlistvec(dxq);
				disposeBetlistVec(bet);
			}
			
			
			betsetWnd.updateBetlistVec(BetListVec);
		}
		
		
		//删除比赛
		Calendar lastdaydeadline = Calendar.getInstance();
		
		lastdaydeadline.set(Calendar.HOUR_OF_DAY, 12);
		
		lastdaydeadline.set(Calendar.MINUTE, 0);
		
		Long currenttime2 = System.currentTimeMillis();
		
		
		
		if(currenttime2 > lastdaydeadline.getTimeInMillis() && currenttime2 - lastdaydeadline.getTimeInMillis() < 220*60*1000){
			for(Iterator<String[]> iterator = BetListVec.iterator(); iterator.hasNext();){
				String[] item = iterator.next();
				java.util.Date startTimeDate = dfmin.parse(item[BETRESINDEX.TIME.ordinal()]);
				
				
				
				
				
				if(startTimeDate.getTime() < lastdaydeadline.getTimeInMillis() && !item[BETRESINDEX.BETRES.ordinal()].equals("-")
						&& System.currentTimeMillis() - startTimeDate.getTime() >= 180*60*1000 ){					
					System.out.println(dfmin.format(System.currentTimeMillis()) + "删除比赛:" + item[BETRESINDEX.TIME.ordinal()] + item[BETRESINDEX.TEAM.ordinal()]);
					iterator.remove();
					continue;
				}
				
				if(startTimeDate.getTime() < lastdaydeadline.getTimeInMillis() && currenttime2 - startTimeDate.getTime() > 200*60*1000){
					System.out.println(dfmin.format(System.currentTimeMillis()) + "超时过多，删除比赛:" + item[BETRESINDEX.TIME.ordinal()] + item[BETRESINDEX.TEAM.ordinal()]);
					iterator.remove();
				}
				
			}
		}
			
		
			

			
		
		
		
		
		
		
		
		
		
		

		
		lockeBetListVecDetails.writeLock().unlock();

		
	}catch(Exception e){
		e.printStackTrace();
		lockeBetListVecDetails.writeLock().unlock();
	}
		
		
	}
	
	

	
	
	public  Vector<GameDetails> getgamedetails(){
		return dxqDetailsWnd.getgameDetailsVec();
	}
	
	
	
	public  Vector<String[]> getbetlistvec(){
		return BetListVec;
	}
	

	public  void disposeBetlistVec(boolean autobet){
		try{
			SimpleDateFormat dfSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String currenttimestr = dfSec.format(System.currentTimeMillis());
			
			for(int i = 0; i < BetListVec.size(); i++){
				
				String[] item = BetListVec.elementAt(i);
				
				if(item[BETRESINDEX.BETRES.ordinal()].equals("-") && autobet){
					
					Vector<GameDetails> gamedetailsvec = dxqDetailsWnd.getgameDetailsVec();
					
					for(int j = 0; j < gamedetailsvec.size(); j++){
						
						GameDetails onegame = gamedetailsvec.elementAt(j);
						
						if(item[BETRESINDEX.TEAM.ordinal()].equals(onegame.teamh + "-vs-" + onegame.teamc) && item[BETRESINDEX.TIME.ordinal()].equals(onegame.datetime)){
							
			        		Vector<String[]> odds = onegame.getodds();
			        		
			        		
			        		
			        		String gid = "";
			        		
			        		for(int kk = 0; kk < odds.size(); kk++){
			        			if(odds.elementAt(kk)[HGODDSINDEX.PRIOTITY.ordinal()].equals("1") && odds.elementAt(kk)[HGODDSINDEX.TYPE.ordinal()].equals("inplay")){
			        				gid = odds.elementAt(kk)[HGODDSINDEX.GID.ordinal()];
			        			}
			        		}
			        		
			        		if(gid.equals("")){
			        			continue;
			        		}
			        		
			            	
			        		String gnum = "";
			        		String type = "";
			        		
			        		gnum = item[BETRESINDEX.GNUMH.ordinal()];
			        		type = "H";

			        		int gold = betsetWnd.getbetamount();
			        		
			        		System.out.println(dfSec.format(System.currentTimeMillis()) +  "投注：" + Arrays.toString(item));

			            	String[] res = HGbethttp.doBetDXQ(this,gid, gnum, type, gold, item[BETRESINDEX.CURRENTPK.ordinal()]);
			            	
			            	if(res[0].equals("1")){
			            		
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRATIO.ordinal()] = res[1];
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRES.ordinal()] = "成功提交注单";
			            		BetListVec.elementAt(i)[BETRESINDEX.BETTIME.ordinal()] = currenttimestr;
			            		BetListVec.elementAt(i)[BETRESINDEX.BETGOLD.ordinal()] = Integer.toString(gold);
			            		System.out.println(dfSec.format(System.currentTimeMillis()) + "成功提交注单" + ":" + Arrays.toString(item));
			            	}else if(res[0].equals("0")){
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRATIO.ordinal()] = res[1];
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRES.ordinal()] = "提交注单待确认";
			            		BetListVec.elementAt(i)[BETRESINDEX.BETTIME.ordinal()] = currenttimestr;
			            		BetListVec.elementAt(i)[BETRESINDEX.BETGOLD.ordinal()] = Integer.toString(gold);
			            		System.out.println(dfSec.format(System.currentTimeMillis()) + "提交注单待确认" + ":" + Arrays.toString(item));
			            	}else if(res[0].equals("-1")){
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRES.ordinal()] = "投注失败";
			            		BetListVec.elementAt(i)[BETRESINDEX.BETTIME.ordinal()] = currenttimestr;
			            		BetListVec.elementAt(i)[BETRESINDEX.BETGOLD.ordinal()] = Integer.toString(gold);
			            		System.out.println(dfSec.format(System.currentTimeMillis()) + "投注失败" + ":" + Arrays.toString(item));
			            	}else if(res[0].equals("-2")){
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRES.ordinal()] = "超过信用余额";
			            		BetListVec.elementAt(i)[BETRESINDEX.BETTIME.ordinal()] = currenttimestr;
			            		BetListVec.elementAt(i)[BETRESINDEX.BETGOLD.ordinal()] = Integer.toString(gold);
			            		System.out.println(dfSec.format(System.currentTimeMillis()) + "超过信用余额" + ":" + Arrays.toString(item));
			            	}else if(res[0].equals("-3")){
			            		BetListVec.elementAt(i)[BETRESINDEX.BETRES.ordinal()] = res[1];
			            		BetListVec.elementAt(i)[BETRESINDEX.BETTIME.ordinal()] = currenttimestr;
			            		System.out.println(dfSec.format(System.currentTimeMillis()) + res[1] + ":" + Arrays.toString(item));
			            	}else if(res[0].equals("100")){
			            		System.out.println(dfSec.format(System.currentTimeMillis()) +"hold on" + item[BETRESINDEX.TEAM.ordinal()] + item[BETRESINDEX.CURRENTPK.ordinal()]);
			            	}
							
						}
						
					}
				}else if(item[BETRESINDEX.BETRES.ordinal()].equals("提交注单待确认")){
					
					
					
					
					
					if(System.currentTimeMillis() - dfSec.parse(item[BETRESINDEX.BETTIME.ordinal()]).getTime() >= 2*60 *1000){
						continue;
					}
					
					
					
					int res = StoneAgeClient.hgbet.notconfirmGame(item[BETRESINDEX.TEAM.ordinal()].split("-vs-")[0].replace(" [中]", ""));
					
					if(res == 1){
						item[BETRESINDEX.BETRES.ordinal()] = "成功提交注单";
					}else if(res == -1){
						//never bet twice
						//BetListVec.elementAt(i)[BETRESINDEX.BETRES.ordinal()] = "投注失败";
						
						System.out.println("投注失败 bug nerver bet twice!");
						
					}
					
				}else if(item[BETRESINDEX.BETRES.ordinal()].equals("投注失败")){
					//todo 继续投?
				}
				
			}
			
			
			saveBetlistVectofile();
			
			
			
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
/*	public  double getbetratio(){
		return betlistwnd.getbetratio();
	}*/
	
	public double getminbetratio(){
		return betsetWnd.getminbetratio();
	}
	
	public double getmaxbetratio(){
		return betsetWnd.getmaxbetratio();
	}
	
	
	
	public  void constructbetlistvec(Vector<GameDetails> dxq){
		
		try{
			
			SimpleDateFormat dfSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			
			Vector<String> tmpdxqpans = betsetWnd.getbetdxqpans();
			String tmprqpanstr = betsetWnd.getbetrqpans();
			
			
			double rqp_f = 0.0f;
			rqp_f = Common.pankouStrtoDouble(tmprqpanstr);
			
			int startbettime = betsetWnd.getstartbettime();
			int endbettime = betsetWnd.getendbettime();
			
			double minbetratio = betsetWnd.getminbetratio();
			double maxbetratio = betsetWnd.getmaxbetratio();
			
			int betamount = betsetWnd.getbetamount();
			

			
			if(tmpdxqpans == null || tmpdxqpans.size() == 0){
				return;
			}
			
			if(tmprqpanstr.equals("")){
				return;
			}
			
			
			
			//取出最小的大小盘口
			double betpankou = 10;
			for(int i = 0; i < tmpdxqpans.size(); i++){
				double dxqp = Common.pankouStrtoDouble(tmpdxqpans.elementAt(i));
				if(dxqp < betpankou){
					betpankou = dxqp;
				}
			}
			
			
			
			
			for(int i = 0; i < dxq.size(); i++){
				
				
				GameDetails onegame = dxq.elementAt(i);
				
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				long gametime = df.parse(onegame.datetime).getTime();
				
				
				
				if(onegame.gameresult.contains("-") || System.currentTimeMillis() - gametime > 120 * 60 *1000 || onegame.currentpankou.equals("")){
					continue;
				}
				
				
				
				boolean hasdanshiodd = false;
				double maxdanshipankou = 0.0;
				
				String maxdanshipankouStr = "";
				
				
				//查看所有单式让球盘盘口，然后取出最大的
/*				for(int j = 0; j < onegame.getodds().size() ; j++){
					if(onegame.getodds().elementAt(j)[HGODDSINDEX.TYPE.ordinal()].equals("danshi") ){
						hasdanshiodd = true;
						String danshirqpstr = onegame.getodds().elementAt(j)[HGODDSINDEX.PANKOU.ordinal()];
						double r = Common.pankouStrtoDouble(danshirqpstr);
						
						if(r > maxdanshipankou){
							maxdanshipankou = r;
							maxdanshipankouStr = danshirqpstr;
							}
						
					}
				}*/
				
				//只需要一盘
				String danshirqpstr = "";
				for(int j = 0; j < onegame.getodds().size() ; j++){
					if(onegame.getodds().elementAt(j)[HGODDSINDEX.TYPE.ordinal()].equals("danshi") && onegame.getodds().elementAt(j)[HGODDSINDEX.PRIOTITY.ordinal()].equals("1")){
						hasdanshiodd = true;
						danshirqpstr = onegame.getodds().elementAt(j)[HGODDSINDEX.PANKOU.ordinal()];
						double r = Common.pankouStrtoDouble(danshirqpstr);
						maxdanshipankou = r;
						
						
					}
				}
				
				
				
				
				if(hasdanshiodd == true){
					
					
					for(int j = 0; j < onegame.getodds().size() ; j++){
						if(onegame.getodds().elementAt(j)[HGODDSINDEX.TYPE.ordinal()].equals("inplay") && 
								onegame.getodds().elementAt(j)[HGODDSINDEX.PRIOTITY.ordinal()].equals("1")){
							
							String tmpinplayxqp = onegame.getodds().elementAt(j)[HGODDSINDEX.U.ordinal()].replace("U", "");
							tmpinplayxqp = tmpinplayxqp.replace(" ", "");
							
							//已无盘口
							if(tmpinplayxqp.equals("none") || onegame.getodds().elementAt(j)[HGODDSINDEX.UODD.ordinal()].equals("none")){
								break;
							}
							
							int currentScore = Integer.parseInt(onegame.getodds().elementAt(j)[HGODDSINDEX.SCOREH.ordinal()])+
									 Integer.parseInt(onegame.getodds().elementAt(j)[HGODDSINDEX.SCOREC.ordinal()]);
							
							
							double tmpinplayratio = 0.0;
							tmpinplayratio = Double.parseDouble(onegame.getodds().elementAt(j)[HGODDSINDEX.UODD.ordinal()]);
							
							//水位
							if(tmpinplayratio < minbetratio || tmpinplayratio > maxbetratio){
								break;
							}
							
							if(!tmpdxqpans.contains(tmpinplayxqp)){
								break;
							}
							
							double tmpinplayxqp_f = Common.pankouStrtoDouble(tmpinplayxqp);
							
							if(tmpinplayxqp_f - currentScore != betpankou){
								break;
							}
							
							//盘口
							/*if( !tmpdxqpans.contains(tmpinplayxqp) || rqp_f < maxdanshipankou){
								continue;
							}*/
							
							if(  rqp_f < maxdanshipankou){
								break;
							}
							
							String[] currentodd = onegame.getodds().elementAt(j);
							
							
							if(!Common.isNum(onegame.getodds().elementAt(j)[HGODDSINDEX.GAMETIME.ordinal()])){
								break;
							}
							
							int currenttime = Integer.parseInt(onegame.getodds().elementAt(j)[HGODDSINDEX.GAMETIME.ordinal()]);
							
							
							
							//时间
							if(currenttime < startbettime || currenttime > endbettime){
								break;
							}

							
							
							
							int findindex = -1;
							
								
							for(int kk = 0; kk < BetListVec.size(); kk++){
								
								String[] item = BetListVec.elementAt(kk);
								
								if(item[BETRESINDEX.TEAM.ordinal()].equals(onegame.teamh+"-vs-"+onegame.teamc) && 
										item[BETRESINDEX.CURRENTPK.ordinal()].equals(tmpinplayxqp)){
									findindex = kk;
									
									if(item[BETRESINDEX.BETRES.ordinal()].equals("投注失败") || item[BETRESINDEX.BETRES.ordinal()].equals("投注失败，错失水位")){

										System.out.println(dfSec.format(System.currentTimeMillis()) + "重新更新投注失败注单" + item[BETRESINDEX.TEAM.ordinal()] + item[BETRESINDEX.CURRENTPK.ordinal()]);
										
										BetListVec.elementAt(kk)[BETRESINDEX.BETRES.ordinal()] = "-";
										//BetListVec.elementAt(kk)[BETRESINDEX.RATIO.ordinal()] = Double.toString(tmpinplayratio);
										BetListVec.elementAt(kk)[BETRESINDEX.CURRENTPK.ordinal()] = tmpinplayxqp;
										saveBetlistVectofile();
									}
									
									break;
								}
								
								
								
								
								
							}
							
							
							if(findindex == -1){
								String[] newitem = {onegame.league, onegame.datetime, onegame.teamh + "-vs-" + onegame.teamc, currentodd[HGODDSINDEX.SCOREH.ordinal()] + "-"
										+ currentodd[HGODDSINDEX.SCOREC.ordinal()] , currentodd[HGODDSINDEX.GNUMC.ordinal()],
										 currentodd[HGODDSINDEX.GNUMH.ordinal()],
										 danshirqpstr, tmpinplayxqp,
										"-", "-","-","-"};
								
								/*if(BetListVec.size() > 0){
									return;
								}*/
								
								BetListVec.add(newitem);
								
								
								System.out.println(dfSec.format(System.currentTimeMillis()) + "新加投注:" + Arrays.toString(newitem));
								
								
								saveBetlistVectofile();
								
								
								

							}
							
							break;
								
							
						}
					}
					
				}
				
				

				
				
				
				
			}	
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	public  void showbetlistwnd(){
		//betlistwnd.setVisible(true);
		betsetWnd.show();
	}
	
	public  void showDXQ(){
		dxqDetailsWnd.setVisible(true);
	}
	
	public  void setDXQstatecolor(Color c){
		dxqDetailsWnd.setStateColor(c);
	}
	
	public  void setDXQstatetxt(String txt){
		dxqDetailsWnd.setStateText(txt);
	}
	
	public  void setDXQgrabstate(boolean b){
		dxqDetailsWnd.setgrabstate(b);
	}
	
	public  boolean getDXQgrabstate(){
		return dxqDetailsWnd.getgragstate();
	}
	
}
